package com.china08.yxyapi.api.h5.par.study.scoreport.stureport;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.mg.scoreport.Exam;
import com.china08.yxyapi.entity.mg.scoreport.Exam.ThanksUser;
import com.china08.yxyapi.repository.mg.scoreport.ExamRepository;
import com.china08.yxyapi.repository.mg.scoreport.ExamStuReportRepository;
import com.china08.yxyapi.security.profile.YxyProfile;

/**
 * 学生考试报告————家长感谢老师
 * 
 */
@CrossOrigin
@RestController
public class ExamStuReportThankController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExamStuReportThankController.class);

    @Autowired
    private ExamRepository examRepository;

    @Autowired
    private ExamStuReportRepository examStuReportRepository;

    @RequestMapping(value = "/api_yw/h5/par/study/scoreport/stureport/thank", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response, @RequestParam String id)
            throws ParseException {

        Exam exam = examRepository.findOne(id);
        List<ThanksUser> thankLst = exam.getThankUsers();
        ThanksUser thanksUser = exam.new ThanksUser();

        YxyProfile profile = getProfile(request, response);

        LOGGER.info("成绩分析学生报告——用户id：" + profile.getId());

        thanksUser.avatar = profile.getUserAvator();
        thanksUser.user_id = profile.getId();
        thanksUser.user_nick = profile.getUserNick();
        if (thankLst == null) {
            thankLst = new ArrayList<Exam.ThanksUser>();
        }
        if (thankLst.size() == 0) {
            thankLst.add(thanksUser);
            exam.setThankUsers(thankLst);
            examRepository.save(exam);
        } else {
            List<String> thanks = thankLst.stream().map(x -> x.user_id).collect(Collectors.toList());
            if (!thanks.contains(thanksUser.user_id)) {
                thankLst.add(thanksUser);
                exam.setThankUsers(thankLst);
                examRepository.save(exam);
            }
        }
    }
}
